package io.lvdaxian.mybatis19.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * 通过 类加载获取Resource 辅助类
 *
 * @author lihh
 */
public class Resources {
  public static Reader getResourceAsReader(String resource) throws IOException {
    return new InputStreamReader(getResourceAsStream(resource));
  }
  
  /**
   * 根据 名称加载类
   *
   * @param classPath class 路径
   * @return 返回 将className 转换为 Class
   * @author lihh
   */
  public static <T> Class<T> classForName(String classPath) {
    try {
      Class<?> clazz = Class.forName(classPath);
      return (Class<T>) clazz;
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static InputStream getResourceAsStream(String resource) throws IOException {
    ClassLoader[] classLoaders = getClassLoaders();
    
    for (ClassLoader classLoader : classLoaders) {
      // 通过 loader 加载资源的 inputStream
      InputStream inputStream = classLoader.getResourceAsStream(resource);
      if (null != inputStream)
        return inputStream;
    }
    throw new IOException("Could not find resource " + resource);
  }
  
  private static ClassLoader[] getClassLoaders() {
    return new ClassLoader[]{
        ClassLoader.getSystemClassLoader(),
        Thread.currentThread().getContextClassLoader()
    };
  }
}
